
package com.yzkj.cpjxc.business.framework.utils;

import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.stereotype.Component;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * XML 序列化与反序列化工具类
 * 在对象中可以用以下的注解 解决object <=> xml的映射问题
 * @XStreamAlias 别名注解(类、字段）
 * @XStreamAsAttribute 转换成属性 (字段)
 * @XStreamOmitField 忽略字段（字段）
 * @XStreamConverter 注入转换器（对象）
 * @XStreamImplicit 隐式集合(集合字段）
 * 可以查看 http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html
 * TODO javadoc for com.chkj.framework.utils.XmlConvertUtils
 */
@Component
public class XMLConvertUtils {

	// Convert Object to XML
	private Marshaller marshaller;
	
	// Convert XML to Object 
	private Unmarshaller unmarshaller;

	public Marshaller getMarshaller() {
		return marshaller;
	}

	public void setMarshaller(Marshaller marshaller) {
		this.marshaller = marshaller;
	}

	public Unmarshaller getUnmarshaller() {
		return unmarshaller;
	}

	public void setUnmarshaller(Unmarshaller unmarshaller) {
		this.unmarshaller = unmarshaller;
	}

	/**
	 * 对象转换为xml
	 */
	public void objectToXML(Object object, String filepath) throws IOException {

		try (FileOutputStream os = new FileOutputStream(filepath);) {
			getMarshaller().marshal(object, new StreamResult(os));
		}
	}

	/**
	 * xml转换object
	 */
	public Object xmlToObject(String xmlfile) throws IOException {

		try(FileInputStream is = new FileInputStream(xmlfile);){
			return getUnmarshaller().unmarshal(new StreamSource(is));
		}
	}

}
